<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/19/019
 * Time: 17:06
 */

namespace App\Controller;


use App\Model\BlogModel;
use App\Model\CommentModel;
use App\Model\UserModel;
use lib\View;

class BlogController
{
   public function bloglist(){
       $username=isset($_SESSION['username'])?$_SESSION['username']:'';
       $blog=new BlogModel('blog','pid');
       $blogs=$blog->get(['uname'=>$username]);

      // print_r($res);exit();
       //echo $username;exit();
    return new View('bloglist',['username'=>$username,'blogs'=>$blogs]);
   }
   public function new_blog(){
       $username=isset($_SESSION['username'])?$_SESSION['username']:'';
       $blog=new BlogModel('blog','pid');
       $blogs=$blog->get();
      //print_r($blogs);exit();
       foreach ($blogs as $k=>$v){
           if ($v['uname']==$username){
               unset($blogs[$k]);
           }
       }
       return new View('bloglist',['blogs'=>$blogs]);
   }
   public function readblog(){
       $bid=$this->input('bid');

       $blog=new BlogModel('blog','pid');
       $ablog=$blog->get(['bid'=>$bid]);
       //print_r($ablogs);exit();
        $_SESSION['ablog']=$ablog;
       $user=new UserModel('user','uid');
       $blogcomments=$user->join(['blogcomment'=>'uid'],['blogcomment.tid'=>$bid]);
       return new View('readblog',['blogcomments'=>$blogcomments]);

   }
   public function addblog(){
       $username=isset($_SESSION['username'])?$_SESSION['username']:'';
       return new View('addblog');
   }
   public function add_blog(){
       $uname=$this->input('uname');
       $blogtitle=$this->input('blogtitle');
       $blogdetail=$this->input('blogdetail');
       $blogcontent=$this->input('blogcontent');
       $blog_create=date('y-m-d h:i:s',time());
       $b=$_FILES['blogsrc'];
       $blog=new BlogModel('blog','bid');
       $blogsrc=$blog->checkimg($b);
       $blogArray=[
           'uname'=>$uname,
           'blogtitle'=>$blogtitle,
           'blogdetail'=>$blogdetail,
           'blogcontent'=>$blogcontent,
           'blog_create'=>$blog_create,
           'blogsrc'=>$blogsrc
       ];
     if ($blog->save($blogArray)){
         //$blogs=$blog->get(['uname'=>$uname]);
        // print_r($blogs);exit();

        return new View('addblog');
     }

   }
    public function blog_comment(){
       $comments=$_POST;
       $comments['create_at']=date('y-m-d h:i:s',time());
       //print_r($comments);exit();
        $comment=new CommentModel('blogcomment','cid');

      if ($comment->save($comments)){
          $user=new UserModel('user','uid');
          $blogcomments=$user->join(['blogcomment'=>'uid'],['blogcomment.tid'=>$comments['tid']]);
          return new View('readblog',['blogcomments'=>$blogcomments]);
      }
      //print_r($blogcomments);exit();

    }

    public function input($name)
    {
        return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}